<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/15 14:20
 */

namespace module\user\controller;

use module\user\front\input\ForgetInput;
use module\user\front\input\LoginInput;
use module\user\front\input\RegisterInput;
use module\user\library\UserController;
use module\user\logic\PassportLogic;
use mof\annotation\Inject;
use mof\ApiResponse;
use think\db\exception\DbException;
use think\response\Json;

class Passport extends UserController
{
    #[Inject]
    protected PassportLogic $logic;

    /**
     * 注册
     * @param RegisterInput $register
     * @return Json
     * @throws DbException
     */
    public function register(RegisterInput $register): Json
    {
        //注册并登录
        $this->logic->register($register, $this->auth);
        return ApiResponse::success([
                'user'  => $this->auth->getUser(),
                'token' => $this->auth->getToken()->toArray()
            ]
        );
    }

    /**
     * 登录
     * @param LoginInput $login
     * @return Json
     * @throws DbException
     */
    public function login(LoginInput $login): Json
    {
        $this->logic->login($login, $this->auth);
        return ApiResponse::success([
                'user'  => $this->auth->getUser(),
                'token' => $this->auth->getToken()->toArray()
            ]
        );
    }

    /**
     * 登出
     * @return Json
     */
    public function logout(): Json
    {
        $this->auth->isLogin() && $this->auth->logout();
        return ApiResponse::success();
    }

    public function forget(ForgetInput $body): Json
    {
        $this->logic->resetPassword($body->type, $body->account, $body->password);
        return ApiResponse::success('密码已重置');
    }

    /**
     * 验证token
     * @return Json
     */
    public function verifyToken(): Json
    {
        if (!$this->auth->isLogin()) {
            return ApiResponse::error('Token无效或不存在');
        }
        return ApiResponse::success($this->auth->getUser());
    }

}